//
//  SqliteToEnityController.m
//  sqliteToEnity
//
//  Created by hament on 13-8-12.
//  Copyright (c) 2013年 hament. All rights reserved.
//

#import "SqliteToEnityController.h"
#import "HCoreConfig.h"
#import "HSqlManager.h"

#import "TableEnity.h"
#import "AttributeEnity.h"
#import "AppDelegate.h"
@interface SqliteToEnityController ()


@property (strong) IBOutlet NSSegmentedControl *mySegment;

@property (strong) IBOutlet NSBox *selectBox;
@property (strong) IBOutlet NSBox *configBox;
@property (strong) IBOutlet NSBox *exportBox;

@property (strong) IBOutlet NSTextField *exportTitleLab;
@property (strong) IBOutlet NSTextField *sqliteTitleLab;


@property (strong) IBOutlet NSTextField *sqlitePathRemindTf;
@property (strong) IBOutlet NSTextField *exportRemindTf;



@property (strong) IBOutlet NSArrayController *dataSources;
@property (strong) IBOutlet NSArrayController *attridataSources;

@property (strong) IBOutlet NSButton *export;



- (IBAction)analysic:(NSButton *)sender;
- (IBAction)exportEnity:(NSButton *)sender;
-(void)checkDBPath:(NSString *)path;
-(BOOL)checkExportPath:(NSString *)path;



@end

@implementation SqliteToEnityController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}






-(void)awakeFromNib {
    
self.publicConfig=[HCoreConfig shareConfig];


   
    //当前针对哪个语言转转实体类标识符
    self.classType=[HCoreConfig getObjClassTypeByIndex:0];//默认objc
    
    /*reminder*/
    [self.sqlitePathRemindTf setHidden:YES];
    [self.exportRemindTf setHidden:YES];
    
    
    /*指向符号*/
    self.symbolImage=[NSImage imageNamed:@"arrow.png"];
    
    
    /*nsbox config*/
    //设置标题颜色
    [[self.selectBox titleCell] setTextColor:[NSColor colorWithCalibratedRed:85.0/255.0  green:123.0/255.0  blue:254.0/255.0 alpha:1.0]];
    [[self.configBox titleCell] setTextColor:[NSColor colorWithCalibratedRed:85.0/255.0  green:123.0/255.0  blue:254.0/255.0 alpha:1.0]];
    [[self.exportBox titleCell] setTextColor:[NSColor colorWithCalibratedRed:85.0/255.0  green:123.0/255.0  blue:254.0/255.0 alpha:1.0]];

    
    //设置菜单 
    [self.mySegment setSegmentStyle:NSSegmentStyleTexturedRounded];
    [self.mySegment setSegmentCount:4];
    
//        NSImage * iconImage1=[NSImage imageNamed:@"obj_c.png"];[iconImage1 setSize:NSMakeSize(40,30)];
//        NSImage * iconImage2=[NSImage imageNamed:@"java.png"];[iconImage2 setSize:NSMakeSize(40,30)];
//        NSImage * iconImage3=[NSImage imageNamed:@"c_sharp.png"];[iconImage3 setSize:NSMakeSize(40,30)];
//        NSImage * iconImage4=[NSImage imageNamed:@"C_plus.png"];[iconImage4 setSize:NSMakeSize(40,30)];
//    
//        [self.mySegment setImage:iconImage1 forSegment:0];
//        [self.mySegment setImage:iconImage2 forSegment:1];
//        [self.mySegment setImage:iconImage3 forSegment:2];
//        [self.mySegment setImage:iconImage4 forSegment:3];
    
    [self.mySegment setImageScaling:NSImageScaleNone forSegment:3];
    
    [self.mySegment setLabel:nil forSegment:0];
    [self.mySegment setLabel:nil forSegment:1];
    [self.mySegment setLabel:nil forSegment:2];
    [self.mySegment setLabel:nil forSegment:3];
    
    
    [self.mySegment setLabel:@"Obj-c" forSegment:0];
    [self.mySegment setLabel:@"Java" forSegment:1];
    [self.mySegment setLabel:@"C#" forSegment:2];
    [self.mySegment setLabel:@"C++" forSegment:3];
    
    [self.mySegment setWidth:80 forSegment:0];
    [self.mySegment setWidth:80 forSegment:1];
    [self.mySegment setWidth:80 forSegment:2];
    [self.mySegment setWidth:80 forSegment:3];
    

    
    
    //add the configView
    [self addTheConfigView];
    
    [self configTheExportDesWith:NSLocalizedString(@"ocExportConfig des", nil)];
    
    
}



#pragma mark
#pragma mark ------业务逻辑--------

-(void)checkDBPath:(NSString *)path{

    BOOL isOk=[HCoreConfig isDBPathOkWithPath:path];
    if (isOk) {
        [self.sqlitePathRemindTf setHidden:YES];
        
         NSArray * arr=[HSqlManager getAllEnitysWithPah:self.sqlitePath.stringValue];
        [self.dataSources setContent:arr];

        [self.view.window makeFirstResponder:self.exportFolderFd];
        
    } else{
        
        [self.sqlitePathRemindTf setHidden:NO];

    }

}



-(BOOL)checkExportPath:(NSString *)path{
    BOOL isOk=[HCoreConfig exportFloderOkWithPath:path];
    
    if (isOk) {
        [self.exportRemindTf setHidden:YES];
    } else{
        [self.exportRemindTf setHidden:NO];
    }
    
    return isOk;
    
}




- (IBAction)analysic:(NSButton *)sender {
    NSString * path=[self.sqlitePath.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    [self checkDBPath:path];
    
}


- (IBAction)exportEnity:(NSButton *)sender {
    NSString * path=[self.exportFolderFd.stringValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    //导出
    if ([self checkExportPath:path]) {
        
        NSArray * datas=[self.dataSources content];
        

        
        AppDelegate * appdelegate=(AppDelegate*)[NSApplication sharedApplication].delegate;
        [appdelegate addGlobalRemind];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            //导出实体类
            switch ([HCoreConfig shareConfig].currentLagIndex) {
                case 0:
                    [HCoreConfig exportToOcClass:datas folderPath:path];
                    break;
                case 1:
                    [HCoreConfig exportToJavaClass:datas folderPath:path];
                    break;
                case 2:
                    [HCoreConfig exportToCSharpClass:datas folderPath:path];
                    break;
                case 3:
                    [HCoreConfig exportToCppClass:datas folderPath:path];
                    break;
                    
                default:
                    break;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [appdelegate finishProcessing];
                
            });
            
            
        });
        
        
        
    }
    
    
    
    
}




- (IBAction)changeLanguaeType:(NSSegmentedControl *)sender{

   // NSInteger selectIndex=sender.selectedSegment;

    
    if ([HCoreConfig shareConfig].currentLagIndex==sender.selectedSegment) {
        return;
    } else {
    
        [HCoreConfig shareConfig].currentLagIndex=sender.selectedSegment;

    }
    
    //改变导出说明
    
    
    switch ([HCoreConfig shareConfig].currentLagIndex) {
        case 0:
           [self configTheExportDesWith:NSLocalizedString(@"ocExportConfig des", nil)];
            break;
        case 1:
            [self configTheExportDesWith:NSLocalizedString(@"javaExportConfig des", nil)];
            break;
        case 2:
            [self configTheExportDesWith:NSLocalizedString(@"csExportConfig des", nil)];
            break;
        case 3:
           [self configTheExportDesWith:NSLocalizedString(@"cppExportConfig des", nil)];
            break;
        default:
            break;
    }
    
    
    
    
    //添加设置页面
    [self addTheConfigView];
    
    
    
    //更改可选的class集合
     self.classType=[HCoreConfig getObjClassTypeByIndex:sender.selectedSegment];//默认objc
    
    //更改每个生成的class value
    
    NSArray * tableEnity=[self.dataSources content];
    
    for (TableEnity * tbenity in tableEnity) {
        
        NSArray * attriarr=tbenity.attributes;
        
        for (AttributeEnity * attri in attriarr) {
            NSString * theNewType=[HCoreConfig covertToAttriType:attri.sqliteType];
            attri.objcType=theNewType;
        }
        
        
    }
    
    //刷新数据源,不过最好的做法是reloadtable
   // [self.dataSources setContent:self.dataSources.content]; //只有
    [self.attributeTableView reloadData];
    
    debugLog(@"current select:%ld",(long)sender.selectedSegment);

}

- (IBAction)chooseDBpath:(NSButton *)sender {

    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setCanChooseFiles:YES];
    [panel setResolvesAliases:YES];
    
    NSString *panelTitle = NSLocalizedString(@"Choose a file", @"Title for the open panel");
    [panel setTitle:panelTitle];
    
    NSString *promptString = NSLocalizedString(@"Choose", @"Prompt for the open panel prompt");
    [panel setPrompt:promptString];
    
    SqliteToEnityController *  weakSelf = self;
    
    [panel beginSheetModalForWindow:[weakSelf.view window] completionHandler:^(NSInteger result){
        
        // Hide the open panel.
        [panel orderOut:self];
        
        // If the return code wasn't OK, don't do anything.
        if (result != NSOKButton) {
            return;
        }
        // Get the first URL returned from the Open Panel and set it at the first path component of the control.
        NSURL *url = [[panel URLs] objectAtIndex:0];
       // [weakSelf.pathControl setURL:url];
        self.sqlitePath.stringValue=url.path;
        [weakSelf checkDBPath:url.path];

    }];
}


- (IBAction)chooseExportfolder:(NSButton *)sender {
    
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setAllowsMultipleSelection:NO];
    [panel setCanChooseDirectories:YES];
    [panel setCanChooseFiles:NO];
    [panel setResolvesAliases:YES];
    
//    NSString *panelTitle = NSLocalizedString(@"Choose a file", @"Title for the open panel");
//    [panel setTitle:panelTitle];
    
    NSString *promptString = NSLocalizedString(@"Choose", @"Prompt for the open panel prompt");
    [panel setPrompt:promptString];
    
    SqliteToEnityController *  weakSelf = self;
    
    [panel beginSheetModalForWindow:[weakSelf.view window] completionHandler:^(NSInteger result){
        
        // Hide the open panel.
        [panel orderOut:self];
        
        // If the return code wasn't OK, don't do anything.
        if (result != NSOKButton) {
            return;
        }
        // Get the first URL returned from the Open Panel and set it at the first path component of the control.
        NSURL *url = [[panel URLs] objectAtIndex:0];
        // [weakSelf.pathControl setURL:url];
        self.exportFolderFd.stringValue=url.path;
        [weakSelf checkExportPath:url.path];
    }];
    
    
}


- (IBAction)covertAllTostring:(NSButton *)sender {
    
    //更改每个生成的class value
    NSArray * tableEnity=[self.dataSources content];
    for (TableEnity * tbenity in tableEnity) {
        
        NSArray * attriarr=tbenity.attributes;
        
        for (AttributeEnity * attri in attriarr) {
            NSString * theNewType=[HCoreConfig covertToAttriType:attri.sqliteType];
            attri.objcType=theNewType;
        }
        
        
    }

    //cocoabinding 只有当被绑定的对象通过kvc手段发生变化时, 界面上才会触发刷新; 如果只是单纯的改变绑定的对象的某个属性, cocoabinding并不会触发
    [self.attributeTableView reloadData];
}



//导出转换设置的view
-(void)addTheConfigView{

    [self.ocConfigView setHidden:YES];
    [self.javaConfigView setHidden:YES];
    [self.csConfigView setHidden:YES];

    switch ([HCoreConfig shareConfig].currentLagIndex) {
        case 0:
            self.ocConfigView.frame=self.configPlaceView.frame;
            [self.configBox addSubview:self.ocConfigView];
             [self.ocConfigView setHidden:NO];
            break;
        case 1:
            self.javaConfigView.frame=self.configPlaceView.frame;
            [self.configBox addSubview:self.javaConfigView];
            [self.javaConfigView setHidden:NO];
            break;
        case 2:
            self.csConfigView.frame=self.configPlaceView.frame;
            [self.configBox addSubview:self.csConfigView];
            [self.csConfigView setHidden:NO];
            break;
        case 3:
            
            
            [self.ocConfigView setHidden:YES];
            
            break;
        default:
            break;
    }



}


-(void)configTheExportDesWith:(NSString*)content{
    
    
    //阴影
    NSShadow* newShadow = [[NSShadow alloc] init];
    newShadow.shadowColor = [NSColor orangeColor];
    newShadow.shadowBlurRadius = 4.0;

    //字体
    NSFont * font=[NSFont fontWithName:@"helvetica" size:13];
    
    //颜色
    NSColor * color=[NSColor blueColor];
    
    NSDictionary* attrs = @{NSShadowAttributeName:newShadow,
                            NSFontAttributeName:font,
                            NSForegroundColorAttributeName:color};

    
    
    NSMutableAttributedString* text = [[NSMutableAttributedString alloc] initWithString:content attributes:attrs];
	//[text addAttributes:attrs range:NSMakeRange(0, self.exportDesTv.string.length)];

    [self.exportDesTv.textStorage setAttributedString:text];
}

#pragma mark
#pragma mark ------textfield delegate-------

- (void)textDidChange:(NSNotification *)notification{

  
}



-(void)controlTextDidChange:(NSNotification *)notification{
    
    
    NSTextField * tf=[notification object];
//如果是java,c#的命名空间的话
    if (tf) {
        switch (tf.tag) {
            case 10://cs
            case 11://java
                self.publicConfig.currentNameSpace=tf.stringValue;
                break;
            default:
                break;
        }
    }
    
}

- (void)textDidBeginEditing:(NSNotification *)notification{




}


#pragma mark
#pragma mark ------KVO/KVC--------
- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {
    
    
    debugLog(@"keyPath:%@",keyPath);
    
    if([self.sqlitePath isEqual:object]){
        
        NSString * path=[change objectForKey:NSKeyValueChangeNewKey];
        debugLog(@"path1:%@",path);
        
    } else if (object==self.exportFolderFd){
        
        NSString * path=[change objectForKey:NSKeyValueChangeNewKey];
        
        debugLog(@"path 2:%@",path);
  
    }
    
    
}



@end
